<?php defined('SYSPATH') or die('No direct script access.');




class Event_Model extends Model {

	/**
	  * Parent constructor - creates the db object
	  */
	public function __construct()
	{
		// load database library into $this->db (can be omitted if not required)
		parent::__construct();
	}
	
    /**
     * Convert from php unix timestamp date to MySQL text formatted date
     * @param integer php unix timestamp date
     * @return string MySQL text formatted date
     */
    static public function php_to_mysql_date($php_date){
        return date( 'Y-m-d H:i:s', $php_date );   
    }
    
    /**
     * Convert from MySQL text formatted date to php unix timestamp date
     * @param string MySQL text formatted date
     * @return integer php unix timestamp date      
     */
    static public function mysql_to_php_date($mysql_date){
        return strtotime( $mysql_date ); 
    }

	/**
	 * Add a new event
	 * @param integer host id (current user id)
     * @param string event name
     * @param string event description
     * @param integer event start time in unix timestamp format
     * @param integer event end time in unix timestamp format
     * @param char event scope, valid values are 'P'=>'Private', 'R'=>'Restricted', 'G'=>'Global'
     * @param string event host name
     * @param string event contact phone number
     * @param string event contact email address
     * @param string event location, street address
     * @param string event location, city
     * @param string event location, state
     * @param string event location, zip code
	 * @return integer id for newly created event
	 */
	public function add_event(
        $user_id, $name, $description, $start_time, $end_time, 
        $scope, $host_name, $phone, $email,
        $street, $city, $state, $zip_code)
	{
        //Convert time from php unix timestamp to MySQL text format
        $start_time=$this->php_to_mysql_date($start_time);
        $end_time=$this->php_to_mysql_date($end_time);
        $created_time=$this->php_to_mysql_date(time());
        
        // Save location info for event into database first and obtain the location id
        $result=$this->db->insert('address',
            array('streetaddress'=>$street,'city'=>$city,'state'=>$state,'zip'=>$zip_code));
        $location_id=$result->insert_id();
        
        // Save event info into database and obtain event id
        $result=$this->db->insert('eventdetail',array('name'=>$name, 'description'=>$description, 
            'starttime'=>$start_time, 'endtime'=>$end_time, 'createdtime'=>$created_time,  
            'userid'=>$user_id, 'scope'=>$scope, 
            'hostname'=>$host_name, 'phone'=>$phone, 'email'=>$email, 'locationid'=>$location_id));         
        $event_id=$result->insert_id();
        
        // Save host (current user) as first attending guest of newly created event
        $result=$this->db->insert('event_user',
            array('eventid'=>$event_id, 'guestid'=>$user_id, 'attendingstatus'=>'Y', 'approved'=>'1', 
                'approvedtime'=>$created_time, 'statusmodifiedtime'=>$created_time));
		return $event_id;
        
	}
    
    /**
     * Update an event
     * @param integer host id (current user id)
     * @param integer id of event to modify
     * @param string event name
     * @param string event description
     * @param integer event start time in unix timestamp format
     * @param integer event end time in unix timestamp format
     * @param char event scope, valid values are 'P'=>'Private', 'R'=>'Restricted', 'G'=>'Global'
     * @param string event host name
     * @param string event contact phone number
     * @param string event contact email address
     * @param string event location, street address
     * @param string event location, city
     * @param string event location, state
     * @param string event location, zip code
     * @return boolean return whatever event with given id is updated
     */
    public function update_event(
        $user_id, $event_id, $name, $description, $start_time, $end_time,
        $scope, $host_name, $phone, $email,
        $street, $city, $state, $zip_code)
    {
        //Convert time from php unix timestamp to MySQL text format
        $start_time=$this->php_to_mysql_date($start_time);
        $end_time=$this->php_to_mysql_date($end_time);

        
        $result=$this->db->select('location_id')->from('eventdetail')
            ->where(array('id'=>$event_id, 'userid'=>$user_id))
            ->get();
        // Event with specified event id and host id does not exist
        if($result->count()==0){
            return false;
        }  
            
        $location_id=$result->current()->locationid;
            
        $this->db->update('address', 
            array('streetaddress'=>$street,'city'=>$city,'state'=>$state,'zip'=>$zip_code), 
            array('id'=>$location_id));            
                   
        $result=$this->db->update('eventdetail', 
            array('name'=>$name, 'description'=>$description, 
            'starttime'=>$start_time, 'endtime'=>$end_time,
            'scope'=>$scope, 'hostname'=>$host_name, 'phone'=>$phone, 'email'=>$email), 
            array('id'=>$event_id, 'userid'=>$user_id));
            
        return true;
    }
    
    /**
     * Delete a event from database, given event id and host user id
     * @param integer event id
     * @param integer event host user id
     * @return return true if event with id specified and hosted by $user_id is deleted from database
     */
    public function delete_event($event_id, $user_id){
        $result=$this->db->select('locationid')
            ->from('eventdetail')
            ->where(array('id'=>$event_id, 'userid'=>$user_id))
            ->get();
            
        if($result->count()==0)
            return false;
        $location_id=$result->current()->locationid;  
        $this->db->delete('address', array('id'=>$location_id));
        $this->db->delete('eventdetail', array('id'=>$event_id));
        return true;
    }
    
    /**
     * Get a list of event viewable by a user within specific time frame
     * @param integer search start time in unix timestamp format
     * @param integer search end time in unix timestamp format
     * @param bool use only date part of start time, ignore time part
     * @param bool use only date part of end time, ignore time part  
     * @return Database_Result a list event viewable by user
     */
    public function get_event_list($user_id, $start_time, $end_time,
        $use_only_start_date=true, $use_only_end_date=true)
    {
        if($use_only_start_date){
            $start_time=strtotime(date('m/d/Y',$start_time)." 00:00:00");
        }
        if($use_only_end_date){
            $end_time=strtotime(date('m/d/Y',$end_time)." 23:59:59");  
        }
        
         //Convert to MySQL text date format
        $start_time=$this->php_to_mysql_date($start_time);
        $end_time=$this->php_to_mysql_date($end_time);
           
        $condition_1=array('g.guestid'=>$user_id, 'e.starttime>='=>$start_time, 'e.starttime<='=>$end_time);
        $condition_2=array('e.starttime<='=>$start_time, 'e.endtime>='=>$start_time);
         
        $event_list=$this->db->select(array('e.id', 'e.name', 'e.description', 'e.starttime', 'e.endtime', 'e.hostname', 'g.attendingstatus'))
            ->from('eventdetail AS e')
            ->join('event_user AS g','e.id', 'g.eventid','INNER')
            ->where($condition_1)
            ->orwhere('g.guestid',$user_id)
            ->where($condition_2)
            ->get();
            
        return $event_list;
    }
    
    /**
     * Determine whatever current user can view a specific event
     * @param integer event id     
     * @param integer user id
     * @return boolean return true if user can view the event
     */
    public function can_view_event($event_id, $user_id){
        return true; // THIS FUNCTION NEED TO BE UPDATED
    }
    
    /**
     * Get detail information about a specific event given event id
     * @param integer event id
     * @return stdClass return detail information regarding to the event, or null if event does not exist
     */
    public function get_event_detail($event_id){
        $resultset=$this->db->from('eventdetail')
            ->where('id',$event_id)
            ->get();
        if($resultset->count()==0)
            return null;
            
        $event=$resultset->current();
        //Convert MySQL time format to Unix timestamp 
        $event->starttime=$this->mysql_to_php_date($event->starttime);
        $event->endtime=$this->mysql_to_php_date($event->endtime);
         
        $location=$this->db->from('address')
            ->where('id',$event->locationid)
            ->get()->current();
        
        // Save event and location info into resultset variable
        $resultset=new stdClass();       
        $resultset->event=$event;
        $resultset->location=$location;
        return $resultset;   
    }
    /**
     * Search for events by name and description using MySQLs full-text search
     * @param string input
     * @return Database_Result search results
     */
    public function search_fulltext($input) {
        $result = $this->db->select(array('id', 'name'))
                           ->from('eventdetail')
                           ->where('match(name,description) against(\''.$input.'\')')
                           ->get();
        return $result;
    } 
}
